import { createAsyncThunk } from '@reduxjs/toolkit';
import axios, { AxiosError } from 'axios';
import { API } from '../../helpers/API';
import { RootState } from '..';

export interface IOneBall {
  id: number;
  name: string;
  image: string;
  price: number;
  count: number;
  title: string;
  description: string;
  favorite?: boolean;
}

export interface IPostDataFromBuy {
  balls: IOneBall[]
  totalSumm: number
}

export interface IResponse {
  balls: IOneBall[], 
  user: {
        email: string,
        fullName: string,
        id: number
        }
  id: number,
  totalSumm: number
    }
export const fetchAddStoryBuySlice = createAsyncThunk<IResponse, IPostDataFromBuy, {state: RootState}>(
	'buyStory/fetchAddStoryBuySlice',
	async (dataFromCart, thunkAPI) => {
		try {
			const token = thunkAPI.getState().authorization.user.token;
			const { data } = await axios.post(`${API}/buyStory`, dataFromCart, {
				headers: { 
					Authorization: `Bearer ${token}`	
				}
			});
			return data;
		} catch (error) {
			if (error instanceof AxiosError) {
				throw new Error(error.response?.data.message);
			}
		}
	}
);

export const fetchGetStoryBuySlice = createAsyncThunk<IResponse[], _, {state: RootState}>(
	'buyStory/fetchGetStoryBuySlice',
	async (_, thunkAPI) => {
		try {
			const token = thunkAPI.getState().authorization.user.token;
			const { data } = await axios.get(`${API}/buyStory`, {
				headers: { 
					Authorization: `Bearer ${token}`	
				}
			});
			return data;
		} catch (error) {
			if (error instanceof AxiosError) {
				throw new Error(error.response?.data.message);
			}
		}
	}
);

export const fetchDeleteStoryBuySlice = createAsyncThunk<_, number, {state: RootState}>(
	'buyStory/fetchDeleteStoryBuySlice',
	async (id, thunkAPI) => {
		try {
			const token = thunkAPI.getState().authorization.user.token;
			const { data } = await axios.delete(`${API}/buyStory/${id}`, {
				headers: { 
					Authorization: `Bearer ${token}`	
				}
			});
			return data;
		} catch (error) {
			if (error instanceof AxiosError) {
				throw new Error(error.response?.data.message);
			}
		}
	}
);